# -*- coding: utf-8 -*-
from wx._core import wxAssertionError
import decimal
import re
import wx
import wx.lib.plot as wxplot
import wx.xrc
import wx.adv
import os
import wx.richtext
import time
import threading
import random
import requests
import json
import datetime
import base64
import lzma
import shutil

import mydata
import mydef
import mypay
import myimage
import mysqldb


class setshangping(wx.Frame):
    def __init__(self, parent,id,name,price,ations,pathfil):
        wx.Frame.__init__(self,parent, title="商品信息",pos = wx.DefaultPosition,size = wx.Size(500,300),style = wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX))
        pathfil = os.path.abspath(pathfil)
        self.bit = wx.StaticBitmap(self,bitmap=mydef.pngSize(500,260, lzma.decompress(base64.b64decode(bytes(myimage.mc11)))))
        def img_dataset(img_data,fx,m):
            if m:
                with open(m,"rb") as redata:
                    img_data = mydef.pngSize(50,50,redata.read())
            return wx.StaticBitmap(self, bitmap=img_data, pos=fx, size=(50,50))
        if os.path.isfile(pathfil):
            #self.bitmap1 = img_dataset(None,(90,5),os.path.join(os.path.dirname(pathfil),list_file[0]))
            self.bitmap2 = img_dataset(None,(230,5),pathfil)
            #self.bitmap3 = img_dataset(None,(360,5),os.path.join(os.path.dirname(pathfil),list_file[2]))
        else:
            bytesdata = base64.b64decode(bytes(myimage.xigua))
            #self.bitmap1 = img_dataset(mydef.pngSize(50,50,bytesdata),(90,5),None)
            self.bitmap2 = img_dataset(mydef.pngSize(50,50,bytesdata),(230,5),None)
            #self.bitmap3 = img_dataset(mydef.pngSize(50,50,bytesdata),(360,5),None)
        self.parent = parent
        self.myid = id
        self.filepick2 = wx.FilePickerCtrl(self.bit,path=pathfil,message="选择图片",wildcard='*.jpg;*.jpeg',pos=(240,60),size = (30,20))
        wx.TextCtrl(self.bit,value=str(id),pos=(195,100),size = (150,24)).Enable(False)
        wx.Button(self.bit, label="序号",pos=(155,100),size = (40,24)).Enable(False)
        wx.Button(self.bit, label="名称",pos=(155,130),size = (40,24)).Enable(False)
        wx.Button(self.bit, label="规格",pos=(155,160),size = (40,24)).Enable(False)
        wx.Button(self.bit, label="价格",pos=(155,190),size = (40,24)).Enable(False)
        self.name = wx.TextCtrl(self.bit,value=name,pos=(195,130),size = (150,24))
        self.ations = wx.TextCtrl(self.bit,value=ations,pos=(195,160),size = (150,24))
        self.price = wx.TextCtrl(self.bit,value=str(price),pos=(195,190),size = (150,24))
        self.buttonsou = wx.Button(self.bit, label="修改",pos=(100,225),size = (300,28))
        self.buttonrem = wx.Button(self.bit, label="删除",pos=(30,120),size = (50,50))
        self.buttonsou.Bind(wx.EVT_BUTTON, lambda evt : self.setupdate(1))
        self.buttonrem.Bind(wx.EVT_BUTTON, lambda evt : self.setupdate(2))
        self.filepick2.Bind(wx.EVT_FILEPICKER_CHANGED,self.updataimg)
        self.Centre()
        self.Bind(wx.EVT_CLOSE,self.onclose)

    def onclose(self,eve):
        self.Destroy()

    def updataimg(self,eve):
        mypath = self.filepick2.GetPath()
        with open(mypath,"rb") as imgdata:
            dataimg = imgdata.read()
        if self.parent:
            self.parent.dict_app[self.myid].SetBitmap(mydef.pngSize(50,50,dataimg))
        self.bitmap2.SetBitmap(mydef.pngSize(50,50,dataimg))
        def mydefrun(n,windows):
            try:
                mypath = os.path.join(mysqldb.seeting.IMG_PATH,n[1])
                if not os.path.isdir(mypath):
                    os.mkdir(mypath)
                shutil.move(n[0],mypath)
                file = os.path.split(n[0])
                myfile = os.path.join(mypath,file[1])
                wx.CallAfter(windows.setupdate,(myfile,4))
            except Exception as a:
                print(a)
        mydef.mythread(self,mydefrun,(mypath,str(self.myid))).start()

    def setupdate(self,mak):
        if mak == 0:
            self.Close()
        elif mak == 1:
            txt1 = self.name.GetValue()
            txt2 = self.ations.GetValue()
            txt3 = self.price.GetValue()
            def mydefrun(n,windows):
                ret = mysqldb.mysql.update_data('inventory',"name='{}',price='{}',ations='{}',path='{}'".format(n[0],n[1],n[2],n[3]),"myid={}".format(n[4]))
                if ret:
                    wx.CallAfter(windows.setupdate,0)
            mydef.mythread(self,mydefrun,(txt1,txt3,txt2,self.filepick2.GetPath(),self.myid)).start()
        elif mak == 2:
            answer = wx.MessageBox("确定删除商品？", "删除提示",wx.YES_NO | wx.CANCEL, self)
            if answer == wx.YES:
                def mydefrun(n,windows):
                    ret = mysqldb.mysql.delete_data('inventory',"myid={}".format(n))
                    if ret:
                        wx.CallAfter(windows.setupdate,3)
                mydef.mythread(self,mydefrun,self.myid).start()
        elif mak == 3:
            if self.parent:
                self.parent.dict_app[self.myid].Destroy()
                self.parent.dict_app.pop(self.myid)
                x,y = 10,10
                for ap in self.parent.dict_app:
                    self.parent.dict_app[ap].SetPosition((x,y))
                    x += 55
                    if x >840:
                        x = 10
                        y += 55
            self.Close()
        elif mak[1] == 4:
            self.filepick2.SetPath(mak[0])


class MainWindow(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self,parent, title="商品结算",pos = wx.DefaultPosition,size = wx.Size(960,540),style = wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX) )
        fontxt = wx.Font(15, wx.FONTFAMILY_SCRIPT, wx.NORMAL, wx.FONTWEIGHT_MEDIUM, False, "华文行楷") # 字体设置
        self.bbtam = wx.StaticBitmap(self,bitmap=mydef.pngSize(960,500, lzma.decompress(base64.b64decode(bytes(myimage.mc1)))))
        self.order = "" # 订单号初始化
        self.price = decimal.Decimal.from_float(0.0) # 价格初始化
        self.list_goods = wx.ListCtrl(self.bbtam,style=wx.LC_REPORT,pos=(10,10),size = (320,450))
        self.list_goods.InsertColumn(0, "商品序号")
        self.list_goods.InsertColumn(1, "商品名称")
        self.list_goods.InsertColumn(2, "商品规格")
        self.list_goods.InsertColumn(3, "商品价格")
        self.button1 = wx.Button(self.bbtam, label="删除商品",pos=(10,465),size = (120,30))
        self.button2 = wx.Button(self.bbtam, label="结算",pos=(210,465),size = (120,30))
        self.sum_int = wx.Button(self.bbtam,label="0",pos=(340,20),size = (150,30))
        self.money = wx.TextCtrl(self.bbtam, value="",pos=(340,70),size = (150,24))
        self.spin = wx.SpinCtrl(self.bbtam,pos=(342,100),size = (50,24),min=1,max=1000)
        self.button3 = wx.Button(self.bbtam, label="额外",pos=(450,100),size = (40,24))
        self.sum_han = wx.Button(self.bbtam,label="零",pos=(340,220),size = (150,30))
        self.inputint = wx.TextCtrl(self.bbtam, value="",pos=(340,380),size = (150,24))
        self.button4 = wx.Button(self.bbtam, label="找零",pos=(340,410),size = (150,30))
        self.richtextlog = wx.richtext.RichTextCtrl(self.bbtam,value=time.strftime("%Y-%m-%d %H:%M:%S"),pos=(500,10),size = (435,450))
        self.strtext1 = wx.TextCtrl(self.bbtam, value="",pos=(620,30),size = (200,30),style=wx.TE_PROCESS_ENTER)
        self.button5 = wx.Button(self.bbtam, label="关闭日志",pos=(500,465),size = (200,30))
        self.button6 = wx.Button(self.bbtam, label="加载日志",pos=(735,465),size = (200,30))
        self.sum_int.SetFont(fontxt)
        self.sum_han.SetFont(fontxt)

        self.button1.Bind(wx.EVT_BUTTON, self.del_goods)
        self.button2.Bind(wx.EVT_BUTTON, lambda evt : self.settlement(int(time.strftime("%Y%m%d%H%M%S")),True))
        self.button3.Bind(wx.EVT_BUTTON, self.zhaoButton)
        self.button4.Bind(wx.EVT_BUTTON, lambda evt : self.settlement(evt,False))
        self.button5.Bind(wx.EVT_BUTTON, self.endButton)
        self.button6.Bind(wx.EVT_BUTTON, self.add_log)
        
        self.strtext1.Bind(wx.EVT_TEXT_ENTER, lambda evt : self.add_goods(evt,False))
        self.Bind(wx.EVT_KEY_DOWN, lambda evt : self.add_goods(evt,True))
        self.bbtam.Bind(wx.EVT_KEY_DOWN, lambda evt : self.add_goods(evt,True))
        self.button5.Bind(wx.EVT_KEY_DOWN, lambda evt : self.add_goods(evt,True))
        self.button6.Bind(wx.EVT_KEY_DOWN, lambda evt : self.add_goods(evt,True))
        self.button2.Bind(wx.EVT_KEY_DOWN, lambda evt : self.add_goods(evt,True))
        self.button1.Bind(wx.EVT_KEY_DOWN, lambda evt : self.add_goods(evt,True))
        self.button4.Bind(wx.EVT_KEY_DOWN, lambda evt : self.add_goods(evt,True))
        self.button3.Bind(wx.EVT_KEY_DOWN, lambda evt : self.add_goods(evt,True))
        self.list_goods.Bind(wx.EVT_KEY_DOWN, lambda evt : self.add_goods(evt,True))

        self.richtextlog.SetStyle(0,20,wx.TextAttr("white","black"))
        self.richtextlog.SetDefaultStyle(wx.TextAttr("red","green"))
        self.Centre()
        self.strtext1.Show(False)
        self.sum_int.Show(False)
        self.sum_han.Show(False)
        self.Bind(wx.EVT_CLOSE,self.onclose)

    def onclose(self,eve):
        self.Destroy()

    def settlement(self,eve,mak):
        if mak and float(self.price)!=0.0:
            msg = ''
            for i in mydata.CACHE:
                msg += str((int(i),mydata.CACHE[i][0],mydata.CACHE[i][1]))
            mssage = " 金额: " + str(float(self.price)) + "元  " + msg
            self.setmak(time.strftime("%Y-%m-%d %H:%M:%S"),mssage,False)
            m = time.gmtime()
            msg = "null,{},{},{},'{}','{}','{}',{}".format(m.tm_year,m.tm_mon,m.tm_mday,time.strftime("%H:%M:%S"),str(float(self.price)),msg,eve)
            def mydefrun(n,windows):
                ret = mysqldb.mysql.insert_data('mylog',"ID,time_year,time_month,time_day,time_datetime,mymoney,content,myid",n)
            mydef.mythread(self,mydefrun,msg).start()
            self.list_goods.DeleteAllItems()
            self.money.SetValue("")
            self.spin.SetValue(0)
            self.inputint.SetValue("")
            self.price = decimal.Decimal.from_float(0.0)
            mydata.CACHE = {}
            self.sum_int.Show(False)
            self.sum_han.Show(False)
        else:
            if float(self.price)==0.0:
                self.setmak(time.strftime("%Y-%m-%d %H:%M:%S"),"没有商品不能结账",False)
            else:
                try:
                    sam = int(self.inputint.GetValue())
                    suu = sam - int(self.price)
                    self.inputint.SetValue(str(suu))
                except ValueError:
                    self.setmak(time.strftime("%Y-%m-%d %H:%M:%S"),"找零不能填入非数字",False)

    def zhaoButton(self,eve):
        try:
            moneyy = float(self.money.GetValue()) * self.spin.GetValue()
            monecc = "100" + str(int(self.money.GetValue())) + str(self.spin.GetValue())
            self.list_goods.Append((monecc,"额外附加",self.spin.GetValue(),str(moneyy)))
            mydef.dict_update(mydata.CACHE,(monecc,moneyy),"add")
            self.price += decimal.Decimal.from_float(moneyy)
            h,i = mydef.ch_zh_han(self.price)
            self.setmak(h,i,True)
            self.sum_int.Show(True)
            self.sum_han.Show(True)
        except ValueError:
            self.setmak(time.strftime("%Y-%m-%d %H:%M:%S"),"额外不能填入非数字",False)

    def endButton(self,eve):
        if self.button5.Label == "关闭日志":
            self.richtextlog.Show(False)
            self.strtext1.Show(True)
            self.button5.SetLabel("打开日志")
        else:
            self.richtextlog.Show(True)
            self.strtext1.Show(False)
            self.button5.SetLabel("关闭日志")

    def del_goods(self, e):
        try:
            goodssum = self.list_goods.GetItemCount()
            for i in range(0,goodssum):
                m = i - (goodssum - self.list_goods.GetItemCount())
                if self.list_goods.IsSelected(m):
                    id_del = mydata.CACHE[self.list_goods.GetItemText(m)][0]
                    mydef.dict_update(mydata.CACHE,(self.list_goods.GetItemText(m),id_del),"del")
                    self.list_goods.DeleteItem(m)
                    self.price -= decimal.Decimal.from_float(id_del)
            if int(self.price) == 0:
                self.price = decimal.Decimal.from_float(0.0)
                self.sum_int.Show(False)
                self.sum_han.Show(False)
            else:
                h,i = mydef.ch_zh_han(self.price)
                self.setmak(h,i,True)
        except Exception as e:
            mydef.erre_log(e)

    def add_goods(self,eve,mak):
        if mak:
            if eve.GetRawKeyFlags() == 1835009:
                self.updategoods()
                self.sum_int.Show(True)
                self.sum_han.Show(True)
            elif str(eve.GetRawKeyFlags()) in mydata.WX_KEY_DICT:
                self.order += mydata.WX_KEY_DICT[str(eve.GetRawKeyFlags())]
        else:
            self.order = self.strtext1.GetLineText(0) 
            self.updategoods()
            self.strtext1.SetValue("")
            self.sum_int.Show(True)
            self.sum_han.Show(True)

    def add_log(self,eve):
        self.button6.Enable(False)
        x,y = self.GetPosition()
        x += 660
        feilpath(self,x,y).Show(True)

    def setmak(self,h,i,mak):
        if mak:
            self.sum_han.SetLabel(h)
            self.sum_int.SetLabel(i)
        else:
            self.richtextlog.AddParagraph(h + " : " + i)
            self.richtextlog.AppendText(" ")
            self.richtextlog.ShowPosition(-1)

    def updategoods(self):
        if self.order in mydata.GOODS_DATA:
            self.list_goods.Append((mydata.GOODS_DATA[self.order]['id'], mydata.GOODS_DATA[self.order]['name'], mydata.GOODS_DATA[self.order]['ations'], mydata.GOODS_DATA[self.order]['price']))
            mydef.dict_update(mydata.CACHE,(mydata.GOODS_DATA[self.order]['id'],mydata.GOODS_DATA[self.order]['price']),"add")
            self.price += decimal.Decimal.from_float(mydata.GOODS_DATA[self.order]['price'])
            h,i = mydef.ch_zh_han(self.price)
            self.setmak(h,i,True)
            self.order = ""
        elif 16 > len(self.order) > 5:
            def mydefrun(n,windows):
                ret = mysqldb.mysql.select_data('name,price,ations',"inventory WHERE myid='{}' LIMIT 1".format(self.order))
                if ret:
                    if ret[0][1] == '':
                        wx.CallAfter(windows.LogMesrun,(2,ret[0]))
                    else:
                        wx.CallAfter(windows.LogMesrun,(3,ret[0]))
                else:
                    wx.CallAfter(windows.LogMesrun,(4,None))
            mydef.mythread(self,mydefrun,int(self.order)).start()
        elif len(self.order) > 16:
            def mydefrun(n,windows):
                rund = mypay.mypay.isorder(n[0])
                if rund:
                    ret = rund(float(n[1]),n[0])
                    if ret:
                        wx.CallAfter(windows.settlement,int(ret),True)
                    else:
                        wx.CallAfter(windows.setmak,time.strftime("%Y-%m-%d %H:%M:%S"),"支付失败",False)
            mydef.mythread(self,mydefrun,(self.order,self.price)).start()
            self.order = ""

    def LogMesrun(self,code):
        if code[0] == 0:
            self.richtextlog.AddParagraph(code[1])
            self.richtextlog.AppendText(" ")
            self.richtextlog.ShowPosition(-1)
        elif code[0] == 1:
            self.updategoods()
        elif code[0] == 2:
            answer = wx.MessageBox("商品价格信息残缺，是否补全", "提示",wx.YES_NO | wx.CANCEL, self)
            if answer == wx.YES:
                setshangping(None,self.order, code[1][0],code[1][1],code[1][2],"").Show(True)
            self.order = ""
        elif code[0] == 3:
            mydata.GOODS_DATA.update({self.order:{"id":self.order,"name":code[1][0],"price":float(code[1][1]),"ations":code[1][2]}})
            self.updategoods()
        elif code[0] == 4:
            answer = wx.MessageBox("商品库里没有这个商品是否联网添加", "添加提示",wx.YES_NO | wx.CANCEL, self)
            if answer == wx.YES:
                mydef.mythread(self,mydef.httpadd,int(self.order)).start()
            else:
                self.order = ""

class Page2(wx.Panel):
    def __init__(self,parent,listapp,windows):
        wx.Panel.__init__(self,parent)
        self.parent = windows
        x = 10
        y = 10
        self.dict_app = {}
        #def binbin(but,im):
        #    but.Bind(wx.EVT_BUTTON, lambda evt : self.openapp(0,im))
        for i in listapp:
            if os.path.isfile(os.path.abspath(i[1])) and len(i[1]) > 1:
                with open(os.path.abspath(i[1]),"rb") as imgdata:
                    bytesdata = imgdata.read()
            else:
                bytesdata = base64.b64decode(bytes(myimage.xigua))
            img = mydef.pngSize(50,50,bytesdata)
            BitmapButtons = wx.BitmapButton(self, bitmap=img, pos=(x,y), size = (50,50))
            BitmapButtons.Bind(wx.EVT_BUTTON, lambda evt, mark=i : self.openapp(0,mark))
            self.dict_app.update({i[0]:BitmapButtons})
            x += 55
            if x >840:
                x = 10
                y += 55

    def openapp(self,eve,id):
        if eve == 0:
            def mydefrun(n,windows):
                ret = mysqldb.mysql.select_data('name,price,ations,path',"inventory WHERE myid='{}' LIMIT 1".format(n))
                if ret:
                    wx.CallAfter(windows.openapp,1,(ret[0],n))
                else:
                    wx.CallAfter(windows.openapp,2,None)
            mydef.mythread(self,mydefrun,id[0]).start()
        elif eve == 1:
            setshangping(self,id[1], id[0][0],id[0][1],id[0][2],id[0][3]).Show(True)
        elif eve == 2:
            self.parent.rettext.SetLabel("数据库查询失败, 请重试或联系开发者")


class shangping(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self,parent, title="商品库",pos = wx.DefaultPosition,size = wx.Size(960,540),style = wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX))
        self.appPagename = 0
        #self.myaui = mydef.mywxaui(self)
        #sp1 = wx.StaticBitmap(self,bitmap=mydef.pngSize(190,110, lzma.decompress(base64.b64decode(bytes(myimage.mc6)))),pos=(0,400),size=(190,100))
        #wx.StaticBitmap(self,bitmap=mydef.pngSize(190,110, lzma.decompress(base64.b64decode(bytes(myimage.mc7)))),pos=(191,400),size=(190,100))
        #sp3 = wx.StaticBitmap(self,bitmap=mydef.pngSize(190,110, lzma.decompress(base64.b64decode(bytes(myimage.mc8)))),pos=(382,400),size=(190,100))
        #sp4 = wx.StaticBitmap(self,bitmap=mydef.pngSize(190,110, lzma.decompress(base64.b64decode(bytes(myimage.mc9)))),pos=(573,400),size=(190,100))
        #sp5 = wx.StaticBitmap(self,bitmap=mydef.pngSize(190,110, lzma.decompress(base64.b64decode(bytes(myimage.mc10)))),pos=(764,400),size=(190,100))
        
        self.buttonabb = wx.Button(self, label="上一页",pos=(10,410),size = (56,30))
        self.buttonadd = wx.Button(self, label="下一页",pos=(70,410),size = (56,30))
        self.buttonend = wx.Button(self, label="加载",pos=(140,410),size = (56,30))
        self.buttonsou = wx.Button(self, label="搜索",pos=(880,410),size = (56,28))
        self.text = wx.TextCtrl(self, value="",pos=(680,410),size = (190,28),style=wx.TE_PROCESS_ENTER)
        self.rettext = wx.StaticText(self,label="",pos=(200,460),size = (500,30),style = wx.ALIGN_CENTRE_HORIZONTAL)
        self.sousuo = wx.Choice(self, choices=["序号"],pos=(630,410),size = (50,30))
        self.sousuo.SetSelection(0)
        self.buttonadd.Bind(wx.EVT_BUTTON, lambda evt, mark=True : self.abbapp(evt,mark))
        self.buttonabb.Bind(wx.EVT_BUTTON, lambda evt, mark=False : self.abbapp(evt,mark))
        self.buttonend.Bind(wx.EVT_BUTTON, self.addapp)
        self.buttonsou.Bind(wx.EVT_BUTTON, self.addend)
        self.Bind(wx.EVT_KEY_DOWN,self.upkey)
        self.Bind(wx.EVT_CLOSE,self.onclose)
        self.text.Bind(wx.EVT_TEXT_ENTER, self.addend)
        self.mynotebook = wx.Notebook(self,size = wx.Size(960,400))
        def mydefrun(n,windows):
            ret = mysqldb.mysql.select_data('myid,path','inventory LIMIT 50 OFFSET {}'.format(n))
            if ret:
                wx.CallAfter(windows.LogMesrun,(2,ret))
        mydef.mythread(self,mydefrun,self.appPagename).start()
        self.mynotebook.Bind(wx.EVT_KEY_DOWN,self.upkey)
        self.Centre()

    def onclose(self,eve):
        self.Destroy()

    def upkey(self,eve):
        self.rettext.SetLabel("")
        if eve.GetRawKeyFlags() == 21823489:
            self.abbapp(eve,True)
        elif eve.GetRawKeyFlags() == 21692417:
            self.abbapp(eve,False)
        elif eve.GetRawKeyFlags() == 1835009:
            self.addend(eve)
        elif eve.GetRawKeyFlags() == 21495809:
            self.sousuo.SetSelection(0)
        elif eve.GetRawKeyFlags() == 22020097:
            self.sousuo.SetSelection(1)

    def addend(self,eve):
        self.rettext.SetLabel("")
        myid = self.text.GetValue()
        if len(myid) > 1:
            try:
                myid = int(myid)
                def mydefrun(n,windows):
                    ret = mysqldb.mysql.select_data('name,price,ations,path',"inventory WHERE myid='{}' LIMIT 1".format(n))
                    if ret:
                        wx.CallAfter(windows.LogMesrun,(4,ret[0],n))
                    else:
                        wx.CallAfter(windows.LogMesrun,(5,n))
                mydef.mythread(self,mydefrun,myid).start()
            except:
                self.rettext.SetLabel("商品序号不能填字母或汉字，必须是纯数字")
        else:
            self.rettext.SetLabel("搜索不能填空值")

    def abbapp(self,eve,mak):
        self.rettext.SetLabel("")
        try:
            if mak:
                self.mynotebook.SetSelection(self.mynotebook.GetSelection()+1)
            else:
                self.mynotebook.SetSelection(self.mynotebook.GetSelection()-1)
        except wxAssertionError:
            if mak:
                self.rettext.SetLabel("已在最后一页")
            else:
                self.rettext.SetLabel("已在第一页")

    def addapp(self,eve):
        self.rettext.SetLabel("")
        self.buttonend.Enable(False) 
        def mydefrun(n,windows):
            ret = mysqldb.mysql.select_data('myid,path','inventory LIMIT 50 OFFSET ' + str(n))
            if ret:
                wx.CallAfter(windows.LogMesrun,(2,ret))
            else:
                wx.CallAfter(windows.LogMesrun,(3,None))
        mydef.mythread(self,mydefrun,self.appPagename).start()

    def LogMesrun(self,code):
        if code[0] == 0:
            self.rettext.SetLabel(code[1])
        elif code[0] == 1:
            while True:
                try:
                    self.mynotebook.SetSelection(self.mynotebook.GetSelection()+1)
                except wxAssertionError:
                    break
            wind = self.mynotebook.GetCurrentPage()
            try:
                x,y = wind.dict_app[list(wind.dict_app)[-1]].GetPosition()
                x += 55
            except:
                x,y = 10,10
            if x >840:
                x = 10
                y += 55
            bytesdata = base64.b64decode(bytes(myimage.xigua))
            img = mydef.pngSize(50,50,bytesdata)
            BitmapButton = wx.BitmapButton()
            BitmapButton.Create(wind, bitmap=img, pos=(x,y), size = (50,50))
            BitmapButton.Bind(wx.EVT_BUTTON, lambda evt, mark=(code[1],'') : wind.openapp(evt,mark))
            wind.dict_app.update({code[1]:BitmapButton})
        elif code[0] == 2:
            self.mynotebook.AddPage(Page2(self.mynotebook,code[1],self),str(self.appPagename))
            self.appPagename += 50
            self.buttonend.Enable(True)
        elif code[0] == 3:
            wx.MessageBox("已加载完毕",caption="提示")
            self.buttonend.Show(False)
        elif code[0] == 4:
            def sou_app(n):
                if int(code[2]) in self.mynotebook.GetCurrentPage().dict_app:
                    return 
                else:
                    try:
                        self.mynotebook.SetSelection(n)
                        return sou_app(n+1)
                    except:
                        return
            sou_app(0)
            setshangping(self.mynotebook.GetCurrentPage(),int(code[2]), code[1][0],code[1][1],code[1][2],code[1][3]).Show(True)
        elif code[0] == 5:
            self.rettext.SetLabel("数据库没有找到到商品, 联网添加中...")
            mydef.mythread(self,mydef.httpadd,int(code[1])).start()


class feilpath(wx.Frame):
    def __init__(self, parent,x,y):
        wx.Frame.__init__(self, parent, title="选择日期", pos=(x,y), size=( 300,300 ))
        self.parent = parent
        self.m_genericDirCtrl2 = wx.adv.CalendarCtrl(self, date=wx.DefaultDateTime,size=( 300,300 ))
        self.m_genericDirCtrl2.Bind(wx.adv.EVT_CALENDAR, lambda evt, : self.add_log(evt,(False,)))
        self.Bind(wx.EVT_CLOSE,self.onclose)

    def onclose(self,eve):
        self.parent.button6.Enable(True)
        self.Destroy()

    def add_log(self,eve,mak):
        if mak[0]:
            if mak[1]:
                self.parent.richtextlog.AddParagraph("/"*34+str("-".join(eve))+"\\"*34)
                self.parent.richtextlog.AppendText(" ")
                for i in mak[1]:
                    self.parent.richtextlog.AddParagraph(str(i))
                    self.parent.richtextlog.AppendText(" ")
                self.parent.richtextlog.AddParagraph("/"*34+str("-".join(eve))+"\\"*34)
            else:
                self.parent.richtextlog.AddParagraph("没有查到 " + str("-".join(eve)) + " 的日志")
            self.parent.richtextlog.AppendText(" ")
            self.parent.richtextlog.ShowPosition(-1)
            self.Close()
        else:
            my_time = self.m_genericDirCtrl2.GetDate()
            my_time = str(my_time).split(" ")[0].split("/")
            def mydefrun(n,windows):
                ret = mysqldb.mysql.select_data("time_datetime,myid,mymoney,content","mylog WHERE time_year={} AND time_month={} AND time_day={}".format(n[0],n[1],n[2]))
                if ret:
                    wx.CallAfter(windows.add_log,n,(True,ret))
                else:
                    wx.CallAfter(windows.add_log,n,(True,None))
            mydef.mythread(self,mydefrun,my_time).start()


class myView( wx.Frame ):
    def __init__( self, parent ):
        wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = "销售报表", pos = wx.DefaultPosition, size = wx.Size( 920,540 ), style = wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX))
        self.pane = wx.Panel(self)
        self.data = None
        self.mycolour = ['red','orange','yellow','green','cyan','blue','purple','black']
        self.pane.SetBackgroundColour("white")
        self.Choice0 = wx.Choice(self.pane,choices=["折线图","条形图"],pos=(10,410))
        self.Choiceyer = wx.Choice(self.pane,choices=["年","月","日"],pos=(100,410))
        self.Button2 = wx.Button(self.pane,label="查询",pos=(700,410))
        self.choice1 = wx.Choice(self.pane,choices=['红色','橙色','黄色','绿色','青色','蓝色','紫色','黑色'],pos=(640,410))
        self.choice1.SetSelection(0)
        self.Choice0.SetSelection(1)
        self.Choiceyer.SetSelection(2)
        self.datem = wx.adv.DatePickerCtrl(self.pane,pos=(780,410))
        self.Choice0.Bind(wx.EVT_CHOICE, lambda evt : self.update(False))
        self.Button2.Bind(wx.EVT_BUTTON, lambda evt : self.update(True))
        self.choice1.Bind(wx.EVT_CHOICE, lambda evt : self.update(False))
        self.plotter = wxplot.PlotCanvas(self.pane)
        self.plotter.SetInitialSize(size=(900, 400))
        self.plotter.ySpec = 10
        #self.plotter.xSpec = 24
        self.plotter.tickLength = (0,0)
        mytm = time.gmtime()
        self.get_data(mytm.tm_year,mytm.tm_mon,mytm.tm_mday)
        self.Centre()
        self.Bind(wx.EVT_CLOSE,self.onclose)

    def onclose(self,eve):
        self.Destroy()

    def redraw(self,data):
        if self.Choiceyer.Selection == 0:
            msg = "年"
        elif self.Choiceyer.Selection == 1:
            msg = "月"
        elif self.Choiceyer.Selection == 2:
            msg = "日"
        if self.Choice0.Selection == 0:
            line= wxplot.PolyLine(data[0], colour=self.mycolour[self.choice1.Selection], width=2)
        else:
            line=wxplot.PolyBars(data[0],fillcolour=self.mycolour[self.choice1.Selection])
        gc = wxplot.PlotGraphics([line], msg + "销售总额：" + data[1] + "元", '', '')
        self.plotter.Draw(gc)

    def update(self,mak):
        if mak:
            my_time = str(self.datem.GetValue()).split(" ")[0].split("/")
            self.get_data(my_time[0],my_time[1],my_time[2])
        else:
            self.redraw(self.data)

    def get_data(self,y,m,d):
        if self.Choiceyer.Selection == 0:
            self.plotter.xSpec = 12
        elif self.Choiceyer.Selection == 1:
            self.plotter.xSpec = 31
        elif self.Choiceyer.Selection == 2:
            self.plotter.xSpec = 24
        def mydefrun(n,windows):
            if n[3] == 24:
                ret = mysqldb.mysql.select_data("time_datetime,mymoney,myid","mylog WHERE time_year={} AND time_month={} AND time_day={}".format(n[0],n[1],n[2]))
            elif n[3] == 31:
                ret = mysqldb.mysql.select_data("time_datetime,mymoney,myid","mylog WHERE time_year={} AND time_month={}".format(n[0],n[1]))
            elif n[3] == 12:
                ret = mysqldb.mysql.select_data("time_datetime,mymoney,myid","mylog WHERE time_year={}".format(n[0]))
            else:
                ret = None
            if ret:
                mydict = {}
                mony = int(sum(map(lambda x:float(x[1]), ret)))
                for i in ret:
                    if n[3] == 24:
                        mydef.dict_update(mydict,(i[0].split(":")[0],int(float(i[1]))),None)
                    elif n[3] == 31:
                        mydef.dict_update(mydict,(str(int(str(i[2])[6:8])),int(float(i[1]))),None)
                    elif n[3] == 12:
                        mydef.dict_update(mydict,(str(int(str(i[2])[4:6])),int(float(i[1]))),None)
                lism = [(i,mydict[i]) for i in mydict]
                windows.data = ([(0, 0)] + [(int(lism[0][0])-1,0)] + lism + [(int(lism[-1][0])+1,0)] + [(n[3], 0)],str(mony))
                wx.CallAfter(windows.redraw,windows.data)
            else:
                windows.data = ([(0, 0),(n[3], 0)],str(0))
                wx.CallAfter(windows.redraw,windows.data)
        mydef.mythread(self,mydefrun,(y,m,d,int(self.plotter.xSpec))).start()


# 待修改
class warehouse(wx.Frame):
    def __init__(self,parent):
        wx.Frame.__init__(self, parent, id = wx.ID_ANY, title = "仓库", size = wx.Size(800,500), style = wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX))
        fontxt = wx.Font(15, wx.FONTFAMILY_SCRIPT, wx.NORMAL, wx.FONTWEIGHT_MEDIUM, False, "华文行楷")
        self.myaui = mydef.mywxaui(self)
        imgmc = mydef.pngSize(800,460, lzma.decompress(base64.b64decode(bytes(myimage.mc5))))
        self.bit = wx.StaticBitmap(self,bitmap=imgmc)
        #self.scroll = wx.ScrolledWindow(self.bit)
        #self.scroll.SetScrollbars(0, 20, 0, 50)
        #self.scroll.SetVirtualSize(800,1500)
        #wx.Button(self.scroll, label="总数量：0",pos=(50,30)).Enable(False)
        self.tctrl = wx.TextCtrl(self.bit,value="商品总量：0",pos=(540,100),size = (180,22))
        wx.TextCtrl(self.bit,value="",pos=(540,150),size = (130,22))
        wx.Button(self.bit,label="搜索",pos=(670,149),size=(50, 24))
        self.update(None)
        self.Centre()
        self.tctrl.SetFont(fontxt)
        self.tctrl.Enable(False)
        self.xigua = mydef.pngSize(50,50, base64.b64decode(bytes(myimage.xigua)))
        self.zsmc = mydef.pngSize(50,50, lzma.decompress(base64.b64decode(bytes(myimage.mc2))))
        self.xxmc = mydef.pngSize(50,50, lzma.decompress(base64.b64decode(bytes(myimage.mc3))))
        self.Bind(wx.EVT_CLOSE,self.onclose)
        self.xy = []

    def onclose(self,eve):
        if self.myaui.app:
            self.myaui.app.Destroy()
        self.Destroy()

    def update(self,res):
        if not res:
            def mydefrun(n,windows):
                ret = mysqldb.mysql.select_data('myid','inventory ORDER BY RANDOM() LIMIT 1')
                if ret:
                    wx.CallAfter(windows.update,ret)
            mydef.mythread(self,mydefrun,None).start()
        else:
            width = 10
            height = 10
            for i in res:
                m = wx.Button(self.bit,label="",pos=(width,height),size=(50, 50))#,style=wx.BORDER_NONE
                m.SetBitmap(self.xigua)
                m.Bind(wx.EVT_BUTTON, lambda evt, mark=m : self.Buttonclick(evt,mark))
                m.Bind(wx.EVT_ENTER_WINDOW, lambda evt, mak=i: self.myauishowtxt(m,mak))
                width += 50

    def Buttonclick(self,eve,us):
        #us.SetBitmapFocus(mydef.pngSize(40,40, base64.b64decode(bytes(myimage.xigua))))
        eve.Skip()
        #us.SetBitmapDisabled(mydef.pngSize(40,40, base64.b64decode(bytes(myimage.xigua))))

    def myauishowtxt(self,eve,id):
        if not self.myaui.app:
            self.myaui.update_app(wx.TextCtrl(self.bit,value=id))
        else:
            self.myaui.app.SetValue(id)
        eve.SetBitmap(self.zsmc)
        if self.xy:
            self.xy[0].SetBitmap(self.xigua)
            self.xy.remove(self.xy[0])
        self.xy.append(eve)

    def update_date(self,car,id):
        if car[0]:
            m = wx.Button(self.bit,label="",pos=car,size=(50, 50))#,style=wx.BORDER_NONE
            m.SetBitmap(self.xigua)
            #m.SetBitmapPressed(self.xxmc)
            m.Bind(wx.EVT_BUTTON, lambda evt, mark=m : self.Buttonclick(evt,mark))
            m.Bind(wx.EVT_ENTER_WINDOW, lambda evt : self.myauishowtxt(m,str(id)))
            #m.Bind(wx.EVT_LEAVE_WINDOW, lambda evt : self.showtxt(m,str(id),False))


class Mypay(wx.Frame):
    def __init__(self,parent):
        wx.Frame.__init__(self, parent, id = wx.ID_ANY, title = "支付设置", size = wx.Size(400,300), style = wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX))
        self.Choice0 = wx.Choice(self,choices=["设置支付信息","查看支付信息"],pos=(10,10))
        self.Choice0.SetSelection(0)
        self.pane1 = wx.Panel(self,pos=(30,50),size=(150,155))
        self.pane2 = wx.Panel(self,pos=(210,50),size=(150,155))
        self.miyao = wx.Button(self, label="设置",size=(150,30),pos=(125,220))
        zfbzf = wx.Button(self.pane1, label="支付宝",size=(120,30), pos=(15,5))
        self.zfbid = wx.TextCtrl(self.pane1,value="",size=(120,24),pos=(15,38))
        wx.Button(self.pane1, label="应用ID",size=(120,30), pos=(15,63)).Enable(False)
        self.zfbm = wx.TextCtrl(self.pane1,value="",size=(120,24),pos=(15,94))
        wx.Button(self.pane1, label="产品码",size=(120,30), pos=(15,120)).Enable(False)
        wxzf = wx.Button(self.pane2, label="微信",size=(120,30), pos=(15,5))
        self.wxshh = wx.TextCtrl(self.pane2,value="",size=(120,24),pos=(15,38))
        wx.Button(self.pane2, label="商户号",size=(120,30), pos=(15,63)).Enable(False)
        self.wxgzh = wx.TextCtrl(self.pane2,value="",size=(120,24),pos=(15,94))
        wx.Button(self.pane2, label="公众账号ID",size=(120,30), pos=(15,120)).Enable(False)
        zfbzf.Enable(False)
        wxzf.Enable(False)
        zfbzf.SetBackgroundColour("red")
        wxzf.SetBackgroundColour("red")
        self.SetBackgroundColour("cyan")
        self.pane1.SetBackgroundColour("blue")
        self.pane2.SetBackgroundColour("blue")
        self.Choice0.Bind(wx.EVT_CHOICE,self.update)
        self.miyao.Bind(wx.EVT_BUTTON,self.seeckz)
        self.Centre()
        self.Bind(wx.EVT_CLOSE,self.onclose)

    def onclose(self,eve):
        self.Destroy()

    def update(self,eve):
        if self.Choice0.Selection == 1:
            self.miyao.SetLabel("查看")
            self.zfbid.Enable(False)
            self.zfbm.Enable(False)
            self.wxshh.Enable(False)
            self.wxgzh.Enable(False)
        else:
            self.miyao.SetLabel("设置")
            self.zfbid.Enable(True)
            self.zfbm.Enable(True)
            self.wxshh.Enable(True)
            self.wxgzh.Enable(True)

    def seeckz(self,eve):
        sseging = mydef.setconfig()
        if self.Choice0.Selection == 1:
            self.zfbid.SetValue(str(base64.b64decode(sseging.zfbid).decode("utf-8")))
            self.zfbm.SetValue(str(base64.b64decode(sseging.zfbmi).decode("utf-8")))
            self.wxshh.SetValue(str(base64.b64decode(sseging.wxid).decode("utf-8")))
            self.wxgzh.SetValue(str(base64.b64decode(sseging.wxmi).decode("utf-8")))
        else:
            myzfbid = self.zfbid.GetValue()
            myzfbm = self.zfbm.GetValue()
            mywxid = self.wxshh.GetValue()
            mywxgzh = self.wxgzh.GetValue()
            sseging.set_cfg("db","zfbid",str(base64.b64encode(myzfbid.encode('utf-8')),"utf-8"))
            sseging.set_cfg("db","zfbmi",str(base64.b64encode(myzfbm.encode('utf-8')),"utf-8"))
            sseging.set_cfg("db","wxid",str(base64.b64encode(mywxid.encode('utf-8')),"utf-8"))
            sseging.set_cfg("db","wxmi",str(base64.b64encode(mywxgzh.encode('utf-8')),"utf-8"))


class MyFrame(wx.Frame):
    def __init__(self,parent):
        wx.Frame.__init__(self, parent, id = wx.ID_ANY, title = "收银", size = wx.Size(618,426), style = wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX))
        fontxt = wx.Font(15, wx.FONTFAMILY_SCRIPT, wx.NORMAL, wx.FONTWEIGHT_MEDIUM, False, "华文行楷")
        self.m_button1 = wx.Button(self, label="编码库",pos=(50,30))
        self.m_button2 = wx.Button(self, label="报表", pos=(50,80))
        self.m_button3 = wx.Button(self, label="扫码", pos=(50,130))
        #self.m_button4 = wx.Button(self, label="仓库", pos=(50,180))
        self.m_button3.Bind(wx.EVT_BUTTON, lambda evt, mark=MainWindow : self.starun(mark))
        self.m_button2.Bind(wx.EVT_BUTTON, lambda evt, mark=myView : self.starun(mark))
        self.m_button1.Bind(wx.EVT_BUTTON, lambda evt, mark=shangping : self.starun(mark))
        #self.m_button4.Bind(wx.EVT_BUTTON, lambda evt, mark=warehouse : self.starun(mark))
        self.Centre()
        self.m_button1.SetFont(fontxt)
        self.m_button2.SetFont(fontxt)
        self.m_button3.SetFont(fontxt)
        #self.m_button4.SetFont(fontxt)
        self.Bind(wx.EVT_PAINT,self.updatepath)
        self.slider = wx.Slider(self, value=125, minValue=0, maxValue=250, pos=(580,290), style=wx.SL_VERTICAL)
        self.slider.SetValue(250)
        self.SetTransparent(250)
        self.slider.SetBackgroundColour("orange")
        self.Bind(wx.EVT_SCROLL,self.myscroll)
        self.Bind(wx.EVT_CLOSE,self.onclose)
        self.Bind(wx.EVT_LEFT_DOWN,self.clock)

    def clock(self,eve):
        x,y = eve.GetPosition()
        if 350 > x > 295 and 375 > y > 360:
            Mypay(None).Show(True)

    def onclose(self,eve):
        self.Destroy()

    def myscroll(self,eve):
        self.SetTransparent(eve.GetInt())

    def starun(self,appweb):
        appweb(self).Show(True)

    def updatepath(self,e):
        imgmc = mydef.pngSize(618,386, lzma.decompress(base64.b64decode(bytes(myimage.mc12))))
        dc = wx.PaintDC(self)
        dc.DrawBitmap(imgmc,0,0,True)
        dc.DrawText("支付设置",300,360)


app = wx.App(False)
MyFrame(None).Show(True)
app.MainLoop()

